//
//  AjFlutterAppspPushPlugin.m
//  PushDemo
//
//  Created by zfl
//  Copyright © 2018 anji-plus 安吉加加信息技术有限公司 http://www.anji-plus.com. All rights reserved.
//

#import "AjFlutterAppspPushPlugin.h"
#import <objc/runtime.h>
#import "JPUSHService.h"
#import "AJPushSDK.h"

@interface AjFlutterAppspPushPlugin()

@end

@implementation AjFlutterAppspPushPlugin

static AjFlutterAppspPushPlugin *sharedInstance;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[AjFlutterAppspPushPlugin alloc] init];
        [sharedInstance initNSNotificationCenter];
    });
    return sharedInstance;
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"aj_flutter_appsp_push" binaryMessenger:[registrar messenger]];
    AjFlutterAppspPushPlugin* instance = [AjFlutterAppspPushPlugin sharedInstance];
    instance.channel = channel;
    [registrar addMethodCallDelegate:instance channel:channel];
    [registrar addApplicationDelegate:instance];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }  else if ([@"getDeviceId" isEqualToString:call.method]) {
        result([UIDevice currentDevice].identifierForVendor.UUIDString ?: @"");
    } else {
        result(FlutterMethodNotImplemented);
    }
}

#pragma mark - AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#ifdef DEBUG
    BOOL pro = NO;
#else
    BOOL pro = YES;
#endif
    NSString *path = [[NSBundle mainBundle] pathForResource:@"AJPush" ofType:@"plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    if (dic && path) {
        [self setDataWithDic:dic];
        [self initAPNSWithOptions:launchOptions apsForProduction:pro];
    } else {
        NSLog(@"初始化失败");
    }
    return YES;
}

/** 成功并上报 DeviceToken */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[AJPushService shareService] registerDeviceToken:deviceToken withUrl:self.host];
}
/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError");
}

- (void)applicationDidEnterBackground:(UIApplication*)application {
    [JPUSHService resetBadge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

#pragma mark - private
- (void)setBadge:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *ConfigurationInfo = call.arguments;
    NSUInteger value = [ConfigurationInfo[@"badge"] integerValue];
    [JPUSHService setBadge:value];
}

//初始化推送服务
- (void)initAPNSWithOptions:(NSDictionary *)launchOptions apsForProduction:(BOOL)isPro{
    [[AJPushService shareService] registerJPushOption:launchOptions appKey:self.jpushAppKey ajAppKey:self.appspAppKey channel:self.jchannel apsForProduction:isPro];
}

//注册推送通知中心
- (void)initNSNotificationCenter {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(noticeBarMessage:)
                          name:kAJPushServiceNoticeBarMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(innerMessage:)
                          name:kAJPushServiceInnerMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(customMessage:)
                          name:kAJPushServiceCustomMessageNotification
                        object:nil];
}
//消息栏通知响应通知
- (void)noticeBarMessage:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    [_channel invokeMethod:@"onMessageClicked" arguments:[self formattedJsonStr:userInfo]];
}

//应用内部响应通知
- (void)innerMessage:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    
    NSMutableDictionary *extras = [NSMutableDictionary dictionary];
    NSString *title = @"";
    NSString *body = @"";
    if ([userInfo[@"aps"][@"alert"] isKindOfClass:[NSDictionary class]]) {
        title = userInfo[@"aps"][@"alert"][@"title"] ?: @"";
        body = userInfo[@"aps"][@"alert"][@"body"] ?: @"";
    }
    for (NSString * key in userInfo.allKeys) {
        if (![key isEqualToString:@"_j_business"] && ![key isEqualToString:@"_j_data_"] && ![key isEqualToString:@"_j_msgid"] &&
            ![key isEqualToString:@"_j_uid"] && ![key isEqualToString:@"aps"]) {
            [extras setObject:userInfo[key] ?: @""forKey:key];
        }
    }
    
    NSDictionary *dic = @{@"content":body,
                          @"title":title,
                          @"extras":extras};
    [_channel invokeMethod:@"onMessageArrived" arguments:[self formattedJsonStr:dic]];
}

//自定义消息响应通知
- (void)customMessage:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    [_channel invokeMethod:@"onMessageArrived" arguments:[self formattedJsonStr:userInfo]];
}

- (void)setDataWithDic:(NSDictionary *)dic {
    AjFlutterAppspPushPlugin* instance = [AjFlutterAppspPushPlugin sharedInstance];
    instance.host = [dic objectForKey:@"AppSpTestURL"];
    instance.appspAppKey = [dic objectForKey:@"APPSP_APPKEY"];
    instance.appspSecretKey = [dic objectForKey:@"APPSP_SECRETKEY"];
    instance.jpushAppKey = [dic objectForKey:@"JG_APPKEY"];
    instance.jchannel = [dic objectForKey:@"JG_CHANNEL"];
}

- (NSString *)formattedJsonStr:(NSDictionary *)dic
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonString;
}
@end
